<template>
  <div class="button-group">
    <p></p>
    <div class="button-item">
      <el-button :disabled="isDisabled('createStage')" type="primary" @click="createStageBtn">新建实验阶段</el-button>
    </div>
    <div class="button-item">
      <el-button :disabled="isDisabled('startExperiment')" type="primary" @click="startExperimentBtn">开始实验
      </el-button>
    </div>
    <div class="button-item">
      <el-button :disabled="isDisabled('saveAsTemplate')" type="primary" @click="saveAsTemplateBtn">
        将当前实验保存为模板
      </el-button>
    </div>
    <div class="button-item">
      <el-button :disabled="isDisabled('stopExperiment')" type="primary" @click="stopExperimentBtn">提前终止实验</el-button>
    </div>
    <div class="button-item">
      <el-button :disabled="isDisabled('saveData')" type="primary" @click="saveDataBtn">保存数据</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import emitter from '@/utils/eventBus'
import {ElMessageBox} from "element-plus";
import {ref} from "vue";

const {proxy}: any = getCurrentInstance()
let experimentInfo = ref({})
let septCount = ref(0)
let templateName = ref("")
let isCreate = ref(false)
let eidC = ref("")
// 处理开始实验按钮点击事件
const createStageBtn = (buttonName: string) => {
    ElMessageBox.prompt('请输入新建实验阶段的数量', '新建实验阶段', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /^\d+$/,
      inputErrorMessage: '请输入有效的数字'
    }).then(({value}) => {
      console.log(`用户输入的数字是: ${value}`)
      // 在这里处理用户输入的数字，例如添加新的实验阶段
      septCount.value = value
      isCreate.value = true
      emitter.emit('getExperimentInfoCline',isCreate)

    }).catch(() => {
      console.log('用户取消了输入')
    })
}

// 处理开始实验按钮点击事件
let isStart = ref(false)
let canSave = ref(false)
const startExperimentBtn = async (buttonName: string) => {
  ElMessageBox.confirm('是否开始实验', '确认开始实验吗？', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then(() => {
    // 在这里处理开始实验的逻辑
    isStart.value = true
    canSave.value = true
    emitter.emit('getStepTableListCline')
    emitter.emit('getExperimentInfoCline',isStart)


  }).catch(() => {
    console.log('用户取消了开始实验')
  })
}

// 是否提前终止实验按钮点击事件
const stopExperimentBtn = async (buttonName: string) => {
  ElMessageBox.confirm('是否提前终止实验', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then(() => {
    proxy.$api.PlcUrlc['end']();
  }).catch(() => {
  })
}

// 是否保存数据按钮点击事件
let isSave = ref(false)
const saveDataBtn = async () => {
  ElMessageBox.confirm('是否保存数据', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then(() => {
    isSave.value = true
    emitter.emit('getStatisticsDataCline')
    // 保存数据后，才可新建实验阶段
    createStageDisabled.value = false;
    // 保存数据后，启用开始试验
    startExperimentDisabled.value = false;
  }).catch(() => {
  })
}

// 处理是否保存数据按钮点击事件
let isSaveTemplate = ref(false)
const saveAsTemplateBtn = async () => {

  ElMessageBox.prompt( '保存为模板', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then(({value}) => {
    // 在这里处理用户输入的数字，例如添加新的实验阶段
    templateName.value = value
    isSaveTemplate.value = true
    emitter.emit('getStepTableListCline', false)
    emitter.emit('updateTemplateListCline')
    // 确认保存为模板后，禁用按钮
    saveAsTemplateDisabled.value = true;
  }).catch(() => {
    console.log('用户取消了输入')
  })
}



const startExperimentOn  = async(stepTableList) => {

  const snowflakeIdResp =  await proxy.$api.PlcDataURl["getSnowflakeId"]();

  // 生成雪花ID
    eidC = snowflakeIdResp.result;
  emitter.emit('Ceid',eidC)
  experimentInfo.euid = eidC;
  // 生成实验编号
  stepTableList.forEach((item) => {
    item.euid = eidC;
  });
  console.log('设定阶段雪花id:', eidC)
  console.log('设定阶段数据:', stepTableList)
  console.log('实验信息:', experimentInfo)

  await proxy.$api.PlcUrlc['start'](stepTableList);
  await proxy.$api.ExperimentUrl['add'](experimentInfo);
}

// 在组件挂载时添加一次性事件监听，避免重复监听
onMounted( async() => {
  // 获取设定阶段数据
  emitter.on('getNowStepTableListCline', async (stepTableList) => {
    //开始实验
    if (isStart.value) {
      isStart.value = false
      startExperimentOn(stepTableList)

      // 开始试验后，禁用新建实验阶段
      createStageDisabled.value = true;
      // 开始试验后，禁用开始试验
      startExperimentDisabled.value = true;
      // 开始试验后，开启保存为模板功能
      saveAsTemplateDisabled.value = false;
    }
    // 保存为模板
    if (isSaveTemplate.value) {
      isSaveTemplate.value = false
      console.log('模板名称:', templateName.value)
      await proxy.$api.TemplateUrl['add']({
        "euid": eidC,
        "heatNo": "C",
        "tname": templateName.value
      });
      emitter.emit('updateTemplateListCline')
    }



  })

  // 新建实验阶段
  emitter.on('experimentInfoDataCline', async (data) => {
    console.log('实验信息 experimentInfoDataCline:', data)
    experimentInfo = data

    if (data != null) {
      console.log('实验信息data:', data)
      if (isCreate.value) {
        isCreate.value = false
        data.septCount = septCount.value
        experimentInfo = data
        const response = await proxy.$api.ExperimentUrl['getSept'](experimentInfo);
        if (response && response.result !== null) {
          // 将接口返回的数据更新到 experimentInfo 中
          emitter.emit('stepTableDataCline', response.result);
        } else {
          console.warn("No data received or result is null.");
        }
      }
    }

  })

  emitter.on('isRunningCline', (data) => {
    stopExperimentDisabled.value = !data
    saveDataDisabled.value = data || !startExperimentDisabled.value
  })

    // 统计数据
  emitter.on('StatisticsTableDataCline', (data) => {
    if (isSave.value) {
      isSave.value = false
      saveStatisticsTableData(data)
    }
    })
})

// 组件卸载时清理事件监听
onUnmounted(() => {
  emitter.off('getNowStepTableListCline')
  emitter.off('experimentInfoDataCline')
  emitter.off('StatisticsTableDataCline')
})

// 保存统计数据
const saveStatisticsTableData = async (data) => {
  console.log('实测阶段数据:', data);
  const response = await proxy.$api.CountURl['save'](data);
  if (response && response.success) {
    ElMessageBox.alert('保存成功', '数据已成功保存', {

      type: 'success',
      confirmButtonText: '确定',
    });
  } else {
    ElMessageBox.alert('保存失败', '数据保存失败，请重试', {
      type: 'error',
      confirmButtonText: '确定',
    });
  }
};


// 模拟按钮禁用状态的标志
const findTemplateDisabled = ref(false)
const loadTemplateDisabled = ref(false)
const createStageDisabled = ref(false)
const startExperimentDisabled = ref(false)
const saveAsTemplateDisabled = ref(true)
const stopExperimentDisabled = ref(true)
const saveDataDisabled = ref(true)

const isDisabled = (buttonName: string) => {
  switch (buttonName) {
    case 'findTemplate':
      return findTemplateDisabled.value
    case 'loadTemplate':
      return loadTemplateDisabled.value
    case 'createStage':
      return createStageDisabled.value
    case 'startExperiment':
      return startExperimentDisabled.value
    case 'saveAsTemplate':
      return saveAsTemplateDisabled.value
    case 'stopExperiment':
      return stopExperimentDisabled.value
    case 'saveData':
      return saveDataDisabled.value
    default:
      return false
  }
}

const handleClick = (buttonName: string) => {
  console.log(`点击了 ${buttonName} 按钮`)
  // 这里可以添加点击按钮后的具体业务逻辑
}
</script>

<style scoped>
.button-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.button-item {
  width: 100%;
}

.el-button {
  width: 100%;
  height: 40px;
  font-size: 16px;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.el-button:hover {
  background-color: #409eff;
  color: #fff;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
}
</style>